package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;

@CanalEventListener
public class SpuListener {
    @Autowired
    public RabbitTemplate rabbitTemplate;

    //监控修改操作
    @ListenPoint(schema = "changgou_goods" ,table = "tb_spu",eventType = {CanalEntry.EventType.UPDATE})
    public void goodsUp(CanalEntry.EntryType entryType, CanalEntry.RowData rowData){
        //将改变之前的数据存入map  键为字段,值为字段对应的值
        HashMap<String, String> oldMap = new HashMap<>();
        rowData.getBeforeColumnsList().forEach((c)->oldMap.put(c.getName(),c.getValue()));

        //将改变之后的数据存入map  键为字段,值为字段对应的值
        HashMap<String, String> newMap = new HashMap<>();
        rowData.getAfterColumnsList().forEach((c)->newMap.put(c.getName(),c.getValue()));

        //判断is_marketable(上架)字段是否从0修改为1
        if ("0".equals(oldMap.get("is_marketable"))&&"1".equals(newMap.get("is_marketable"))){
            //如果是,则将id信息发送至ribbonMQ
            rabbitTemplate.convertAndSend( RabbitMQConfig.GOODS_UP_EXCHANGE,"",newMap.get("id"));

            }
        //判断is_marketable(上架)字段是否从1修改为0
        if ("1".equals(oldMap.get("is_marketable"))&&"0".equals(newMap.get("is_marketable"))){
            //如果是,则将id信息发送至ribbonMQ
            rabbitTemplate.convertAndSend( RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newMap.get("id"));

        }
    }
    //监控删除操作
    @ListenPoint(schema = "changgou_goods" ,table = "tb_spu",eventType = {CanalEntry.EventType.DELETE})
    public void goodsDe(CanalEntry.EntryType entryType, CanalEntry.RowData rowData){
        //将改变之前的数据存入map  键为字段,值为字段对应的值
        HashMap<String, String> newMap = new HashMap<>();
        rowData.getBeforeColumnsList().forEach((c)->newMap.put(c.getName(),c.getValue()));
            //是删除,则将id信息发送至ribbonMQ
            rabbitTemplate.convertAndSend( RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newMap.get("id"));
    }
}
